﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Reflection;
using System.IO;
using System.Diagnostics;

namespace template_dll
{
    public partial class ChildForm : Form
    {
        public ChildForm()
        {
            InitializeComponent();
        }

        private const string namechcol = "Флаг";
        private SqlConnection conn;
        private DataTable dt_rep;
        private delegate void Deleg();
        private Deleg del;
        private int inf_id = 0;
        private DateTime datetime = DateTime.Now;
        
        public static bool DisplayForm(System.Windows.Forms.Form theMDIParent)
        {
            ChildForm f = new ChildForm();
            f.MdiParent = theMDIParent;
            f.WindowState = FormWindowState.Maximized;
            f.Show();
            return true;
        }

        private string GetServ(string filename)
        {
            string str = "";
            using (StreamReader streamReader = new StreamReader(filename))
            {
                while (!streamReader.EndOfStream)
                {
                    str += streamReader.ReadLine();
                }
            }
            return str;
        }

        private void ChildForm_Load(object sender, EventArgs e)
        {
            conn = new SqlConnection(@"Server=" + GetServ("serv.txt") + ";Database=SecurityFA;Integrated Security=True");
            UpdateDGV(conn);
            ActivField(true);

        }


        private void UpdateDGV(SqlConnection con)
        {
            try
            {
                dataGridView1.DataSource = null;
                dt_rep = null;
                dt_rep = (new SqlStorProc()).SqlProcExecWithQueryOneTable(con, "pas_InformSel", 60, null);
                dataGridView1.DataSource = dt_rep.DefaultView;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.ColumnIndex > -1 && e.RowIndex > -1)
                {
                    if (textBox1.ReadOnly == false)
                    {
                        if (MessageBox.Show("Все несохраненные данные будут удалены", "Внимание!", MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
                        {
                            ActivField(false);

                            inf_id = Convert.ToInt32(dataGridView1[0, e.RowIndex].Value);
                            datetime = Convert.ToDateTime(dataGridView1[1, e.RowIndex].Value);
                            textBox1.Text = dataGridView1[2, e.RowIndex].Value.ToString();
                            richTextBox1.Text = dataGridView1[3, e.RowIndex].Value.ToString();
                        }
                    }
                    else
                    {
                        ActivField(false);

                        inf_id = Convert.ToInt32(dataGridView1[0, e.RowIndex].Value);
                        datetime = Convert.ToDateTime(dataGridView1[1, e.RowIndex].Value);
                        textBox1.Text = dataGridView1[2, e.RowIndex].Value.ToString();
                        richTextBox1.Text = dataGridView1[3, e.RowIndex].Value.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            inf_id = 0;
            datetime = DateTime.Now;  
            textBox1.Clear();
            richTextBox1.Clear();
            ActivField(true);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                if (datetime.Date < DateTime.Now.Date) MessageBox.Show("Нельзя менять старые сообщения, только текущего дня!");
                else
                {
                    if (textBox1.Text == "")
                    {
                        MessageBox.Show("Не введена шапка");
                        textBox1.Focus();
                    }
                    else
                    {
                        if (richTextBox1.Text == "")
                        {
                            MessageBox.Show("Не введенj сообщение");
                            richTextBox1.Focus();
                        }
                        else
                        {
                            SqlStorProc.sp_params[] par = new SqlStorProc.sp_params[4];
                            par[0].name = "@inf_id";
                            if (inf_id == 0) par[0].value = null;
                            else par[0].value = inf_id;
                            par[1].name = "@del";
                            par[1].value = false;
                            par[2].name = "@title";
                            par[2].value = textBox1.Text;
                            par[3].name = "@comm";
                            par[3].value = richTextBox1.Text;

                            (new SqlStorProc()).SqlProcExecNonQuery(conn, "pas_InformInsUpdDel", 30, par);
                            UpdateDGV(conn);

                            inf_id = 0;
                            datetime = DateTime.Now;
                            textBox1.Clear();
                            richTextBox1.Clear();

                            ActivField(true);

                            MessageBox.Show("Запись сохранена");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (datetime.Date < DateTime.Now.Date) MessageBox.Show("Нельзя менять старые сообщения, только текущего дня!");
            else
            {
                ActivField(true);
                button4.Enabled = true;
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridView1.CurrentRow.Index > -1)
                    if (MessageBox.Show("Удалить сообщение?", "Внимание", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        SqlStorProc.sp_params[] par = new SqlStorProc.sp_params[2];
                        par[0].name = "@inf_id";
                        par[0].value = dataGridView1[0, dataGridView1.CurrentRow.Index].Value;
                        par[1].name = "@del";
                        par[1].value = true;
                        (new SqlStorProc()).SqlProcExecNonQuery(conn, "pas_InformInsUpdDel", 30, par);
                        UpdateDGV(conn);

                        inf_id = 0;
                        datetime = DateTime.Now;
                        textBox1.Clear();
                        richTextBox1.Clear();
                        ActivField(true);
                    }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void ActivField(bool act)
        {
            if (act)
            {
                textBox1.ReadOnly = false;
                richTextBox1.ReadOnly = false;
                button4.Enabled = false;
            }
            else
            {
                textBox1.ReadOnly = true;
                richTextBox1.ReadOnly = true;
                button4.Enabled = true;
            }
        }
    }
}
